#coding=utf-8
#LightCam 进程守护程序
#init by hfh 20150709

import multiprocessing,subprocess,threading
import socket,os,time,re,traceback,sys
import lc_libs

def func(this):
	#agent_hostname=this['agent_hostname']
	ProcessName=this['ProcessName']
	StartCommand=this['StartCommand']
	Active=this['Active']
	definenumber=this['definenumber']
	operator=this['operator']
	interval=this['interval']
	schedule=this['schedule']
	holiday=this['holiday']
		
	try:
		
		#执行日志文件清理
		#logfilename=lchome+'/log/'+ProcessName.split('.')[0]+'.log'
		#if os.path.getsize(logfilename)>=10*1024*1024:
		#if os.path.getsize(logfilename)>=10:
		#	os.system("cp "+logfilename+" "+logfilename+".old")
		#	os.system("echo \"\">"+logfilename)
		
		#执行进程监控
		comd="ps -elf|grep "+str(ProcessName)+"|grep -v grep|wc -l"
		popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		#判断子进程是否结束
		while True:
			if popen.poll()==None:
				time.sleep(0.1)
				continue
			else:
				break

		#处理程序
		line=popen.stdout.read().strip("\n").strip("\r")
		
		res=lc_libs.lc_operator(int(line),operator,int(definenumber))
		
		if res and int(Active) == 0:
			#停止进程
			comd="ps -ef|grep %s|grep -v grep|awk '{print $2}'" % ProcessName
			popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
			pid=popen.stdout.read().strip("\n").strip("\r")
			comd="kill -9 "+pid
			os.system(comd)
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			logfile.write(logdate+" :Stop "+ProcessName+"\n")
			logfile.flush()
		elif not res and int(Active) == 1:
			#启动进程
			comd=StartCommand
			#print comd
			popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			logfile.write(logdate+" :Start "+ProcessName+"\n")
			logfile.flush()
	except Exception:
		excinfo=traceback.format_exc()
		print excinfo
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()
		time.sleep(1)


if __name__ == "__main__":


	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	
	today=time.strftime('%Y%m%d',time.localtime())
	os.system("mv %s %s.%s" % (logfilename,logfilename,today))
	
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()
	
	agent_hostname=lc_libs.lc_gethostname()
	
#	try:
#		#初始化数据库
#		
#		db=lc_libs.lc_mongodb_operater('127.0.0.1',27017)
#
#		db.connect()
#		Conn=db.getConn()
#		if Conn==None:
#			print "Can not Connect to the MondbDB"
#			exit(0)
#		
#		events_dbname='lc_events'
#		events_tablename='lc_events'
#		
#		history_dbname='lc_history'
#		history_tablename="lc_process"
#		
#		events_db=db.useDatabase(events_dbname)
#		events_table=db.UseCollection(events_db,events_tablename)
#		
#		history_db=db.useDatabase(history_dbname)
#		history_table=db.UseCollection(history_db,history_tablename)
#
#	except Exception:
#		excinfo=traceback.format_exc()
#		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
#		logfile.write(logdate+" 初始化数据库失败:\n"+excinfo+"\n")
#		logfile.flush()
#		exit(0)

	#主程序
	MonitorList = []
	
	for lines in open(confname):
		if lines[0] == '#' or lines.split("\t")[0] not in (agent_hostname,'default'):
			continue

		line=lines.strip('\r\n').split('\t')
		dconf={}
		
		#dconf['agent_hostname']=line[0]
		dconf['ProcessName']=line[1]
		dconf['StartCommand']=line[2]
		dconf['Active']=line[3]
		dconf['definenumber']=line[4]
		dconf['operator']=line[5]
		dconf['interval']=line[6]
		dconf['schedule']=line[7]
		dconf['holiday']=line[8]
	
		MonitorList.append(dconf)

	usedtime=0
	
	while True:
		time.sleep(1)
		realtime=int(time.time())
		
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		holiday_state = lc_libs.lc_isholiday()
		
		threads = []
		for i in MonitorList:
			if int(i['holiday']) == 1 and holiday_state == True:
				continue
				
			time_state = lc_libs.lc_schedule(i['schedule'])
			if time_state == False:
				continue
			
			flag=realtime%int(i['interval'])
			#print flag
			if flag<=usedtime:
				print i
				t = threading.Thread(target=func,args=(i,))
				threads.append(t)
		
		for t in threads:
			t.start()
			while True:
				#print len(threading.enumerate())
				time.sleep(0.01)
				if(len(threading.enumerate()) < 100):
					break

		#排除执行程序导致的时间差
		usedtime=int(time.time())-realtime
		#print "usedtime:%s" % usedtime
